package net.kuhyygy.crawl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class Downloader implements Runnable {

	private String url;

	public Downloader(String url) {
		this.url = url;
	}

	@Override
	public void run() {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			if (!url.startsWith("http")) return;
			URL imgUrl = new URL(url);
			InputStream is = imgUrl.openConnection().getInputStream();
			byte[] buff = new byte[1024];
			bis = new BufferedInputStream(is);
			int lastIndex = url.length();
			if (url.contains("?")) {
				lastIndex = url.indexOf("?");
			}
			String fileName = url
					.substring(url.lastIndexOf("/") + 1, lastIndex);
			bos = new BufferedOutputStream(new FileOutputStream(new File(
					"D:\\feiwen\\" + fileName)));
			int len = 0;
			while ((len = bis.read(buff)) != -1) {
				bos.write(buff, 0, len);
			}
			bos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bos.close();
				bis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
